class_name ScreenManager

extends Control

enum LoadMode {
	OVERLAP,
	REPLACE,
}

var stack: Array[GameScreen]

func _ready():
	catch_first_screen()


func _unhandled_input(event: InputEvent):
	if event is InputEventKey:
		if not event.is_pressed() and event.keycode == KEY_BACKSPACE:
			pop_screen()


func catch_first_screen():
	var first := get_child(0) as GameScreen
	if first != null:
		first.manager = self
		stack.push_back(first)
	else:
		print("No default screen!")
		for child in get_children():
			remove_child(child)
			child.queue_free()


func remove_last_child():
	var last := get_child(-1)
	remove_child(last)
	last.queue_free()


func push_screen(screen: GameScreen, mode: LoadMode = LoadMode.REPLACE):
	screen.manager = self
	screen.load_mode = mode
	stack.push_back(screen)
	if mode == LoadMode.REPLACE:
		remove_last_child()
	add_child(screen)


func pop_screen():
	if stack.is_empty():
		return
	
	var last := stack.pop_back() as GameScreen
	last.manager = null
	remove_last_child()
	
	if last.load_mode == LoadMode.REPLACE and not stack.is_empty():
		add_child(stack[-1])
